package Matrix;

public class Martix {
    private int rows, columns;
    private int[][] elements;
    private static final int MIN_CAPCITY = 3;

    public Martix(int rows, int columns) {
        if (rows >= 0 && columns >= 0) {
            this.rows = rows;
            this.columns = columns;

            if (rows < MIN_CAPCITY) this.rows = MIN_CAPCITY;
            if (columns < MIN_CAPCITY) this.columns = MIN_CAPCITY;

            this.elements = new int[this.rows][this.columns];
        } else {
            throw new IllegalArgumentException("矩阵行列数不能小于0");
        }
    }

    public Martix(int n) {
        this(n, n);
    }

    public Martix() {
        this(0);
    }

    public Martix(int rows, int columns, int[][] values) {
        this(rows, columns);
        for (int i = 0; i < values.length && i < rows; i++) {
            for (int j = 0; j < values[i].length && j < columns; j++) {
                elements[i][j] = values[i][j];
            }
        }
    }

    public int getRows() {
        return rows;
    }

    public int getColumns() {
        return columns;
    }

    public int getValues(int row, int column) {
        if (row >= 0 && row <= this.rows && column >= 0 && column <= this.columns) {
            return this.elements[row][column];
        } else throw new IndexOutOfBoundsException("数组下标越界");
    }

    public void setValues(int row, int column, int value) {
        if (row >= 0 && row <= this.rows && column >= 0 && column <= this.columns) {
            this.elements[row][column] = value;
        } else throw new IndexOutOfBoundsException("数组下标越界");
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("矩阵" + this.getClass().getName() + "(" + this.rows + "x" + this.columns + ")\n");
        for (int i = 0; i < this.rows; i++) {
            for (int j = 0; j < this.columns; j++) {
                sb.append(this.elements[i][j] == 65535?String.format("%5s","∞"):String.format("%5d", this.elements[i][j]));
            }
            sb.append("\n");
        }
        return sb.toString();
    }

    public void setRowsColumn(int rows, int columns) {
        if (rows >= 0 && columns >= 0) {
            if(rows > elements.length || columns > elements[0].length){
                int[][] source = this.elements;
                this.elements = new int[rows][columns];
                for (int i=0;i<this.rows;i++){
                    for (int j=0;j<this.columns;j++){
                        elements[i][j] = source[i][j];
                    }
                }
            }
            this.rows = rows;
            this.columns = columns;
        }else throw new IllegalArgumentException("矩阵行数不能小于0");
    }
}
